package sdk.webview.fmc.com.fmcsdk.activity;

/**
 * Created by ydm on 2020/1/7.
 */

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

import java.io.IOException;

import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.base.BaseActivity;
import sdk.webview.fmc.com.fmcsdk.base.BasePresenter;

public class MediaSurfaceActivity extends BaseActivity {
    private SurfaceView mSurfaceView;
    private MediaPlayer mPlayer;
    private SurfaceHolder holder;
    private String url;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_media_surface;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        initView();
        setVideo();
        setListener();
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    private void initView() {
        mSurfaceView = (SurfaceView) findViewById(R.id.id_surfaceview);
        mPlayer = new MediaPlayer();
        holder = mSurfaceView.getHolder();
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        url = getIntent().getStringExtra("url");
    }

    private void setVideo() {
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                openVideo();
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                mPlayer.reset();
                mPlayer.release();
                mPlayer = null;
            }
        });
    }

    private void openVideo() {
        //重置播放器，避免在切换视频的地址时报错
        mPlayer.reset();
//        Uri uri = Uri.parse("/storage/emulated/0/DCIM/Camera/视频/VID_20200107_171038.mp4");
//        "http://192.168.200.88/api/file/down/1214125304658923520.mp4"
        Uri uri = Uri.parse(url);
        try {
            mPlayer.setDataSource(this, uri);    //设置视频播放的地址
            //给播放器设置holder，确认在哪个播放器上进行播放
            mPlayer.setDisplay(holder);
            //开始准备播放视频
            mPlayer.prepareAsync();    //异步线程播放
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setListener() {
        mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mPlayer.start();   //开始播放
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mPlayer!=null)
        mPlayer.stop();
    }

}